import db from '../db/index.js'
export async function getmajorlist(req, res) {
    const majors = await new Promise((resolve, reject) => {
        const sql = 'SELECT majorid, name FROM major';
        db.query(sql, (err, results) => {
            if (err) return reject(err);
            resolve(results);
        });
    });
    const majorsid = majors.map((item) => { return item.majorid })    
    const submajor = await new Promise((resolve, reject) => {
        const sql = 'select submajorid,name,majorid from submajor where majorid in (?)'
        db.query(sql,[majorsid] , (err, data) => {
            if (err) return reject(err)
            resolve(data)
        })
    })    
    majors.forEach(item => {
        item.submajors = []
        submajor.forEach(subitem =>{
            if(subitem.majorid==item.majorid) item.submajors.push(subitem)
        })    
    });
    res.send({ status: 200, data: majors });
}
export function getmajorinfo(req,res){
        const { condition, val } = req.body
        const sql = `select submajor.name as major_name,submajorid,submajor.desc,teacher.name as teacher FROM submajor 
        inner join teacher on teacher.teacherid = submajor.teacherid  where ${condition}=?
        `
        db.query(sql,val,(err,data)=>{
            if(err) return res.dbno(err)
            if(data.length==0) return res.cc(198,'没有该数据') 
                const majorinfo = data[0]
            const sql1=`select honor, create_time from majorhonor where submajorid=?`
            db.query(sql1,data[0].submajorid,(err,data)=>{
                if(err) return res.dbno(err)
                res.send({status:200,major:majorinfo,honor:data.length!=0?data:[]})
            })
        })


}